<template>
  <div class="chat-container">
    <!-- 消息历史区域 -->
    <div class="message-list" ref="messageContainer">
      <div
        v-for="(message, index) in messages"
        :key="index"
        class="message-item"
        :class="{
          'user-message': message.role === 'user',
          'ai-message': message.role === 'assistant',
        }"
      >
        <div class="message-content">
          <div v-if="message.role === 'user'">{{ message.content }}</div>
          <div v-else v-html="renderMarkdown(message.content)" class="markdown-content"></div>
        </div>
      </div>
      <div v-if="isLoading" class="loading-indicator">
        <div class="typing-indicator">
          <span></span>
          <span></span>
          <span></span>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <textarea
        v-model="inputText"
        @keydown.enter.exact.prevent="sendMessage"
        @keydown.shift.enter.exact="handleShiftEnter"
        placeholder="输入消息..."
        rows="3"
        :disabled="isLoading"
      ></textarea>
      <button @click="sendMessage" :disabled="isLoading || !inputText.trim()">
        <span v-if="!isLoading">发送</span>
        <span v-else>发送中...</span>
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, onMounted } from 'vue'
import { marked } from 'marked'
import DOMPurify from 'dompurify'
import axios from 'axios'

// 配置marked
marked.setOptions({
  breaks: true,
  gfm: true,
})

// 创建axios实例
const api = axios.create({
  baseURL: 'http://localhost:5000', // 根据你的后端地址调整
  timeout: 300000, // 5分钟超时
})

// 消息数据
const messages = reactive([])
const inputText = ref('')
const isLoading = ref(false)
const messageContainer = ref(null)

// 渲染安全的Markdown
const renderMarkdown = (content) => {
  return DOMPurify.sanitize(marked.parse(content))
}

// 处理Shift+Enter换行
const handleShiftEnter = () => {
  inputText.value = inputText.value + '\n'
}

// 发送消息
const sendMessage = async () => {
  const userMessage = inputText.value.trim()
  if (!userMessage || isLoading.value) return

  // 添加用户消息
  messages.push({
    role: 'user',
    content: userMessage,
    timestamp: new Date().getTime(),
  })

  // 清空输入
  inputText.value = ''

  // 设置加载状态
  isLoading.value = true
  scrollToBottom()

  try {
    const response = await api.post('/api/chat', {
      messages: messages.map((m) => ({
        role: m.role,
        content: m.content,
      })),
    })

    // 添加AI响应
    messages.push({
      role: 'assistant',
      content: response.data.content,
      timestamp: new Date().getTime(),
    })
  } catch (error) {
    console.error('API请求失败:', error)
    messages.push({
      role: 'assistant',
      content: '抱歉，请求出错，请稍后再试',
      isError: true,
      timestamp: new Date().getTime(),
    })
  } finally {
    isLoading.value = false
    scrollToBottom()
  }
}

// 自动滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight
    }
  })
}

// 初始化加载历史消息（可选）
onMounted(() => {
  const savedMessages = localStorage.getItem('chatMessages')
  if (savedMessages) {
    messages.push(...JSON.parse(savedMessages))
  }
})
</script>

<style scoped>
.chat-container {
  max-width: 800px;
  margin: 0 auto;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f9f9f9;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f5f5f5;
}

.message-item {
  margin: 12px 0;
  display: flex;
}

.user-message {
  justify-content: flex-end;
}

.ai-message {
  justify-content: flex-start;
}

.message-content {
  max-width: 80%;
  padding: 12px 16px;
  border-radius: 8px;
  word-break: break-word;
  line-height: 1.5;
}

.user-message .message-content {
  background: #1890ff;
  color: white;
}

.ai-message .message-content {
  background: white;
  border: 1px solid #eaeaea;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.markdown-content {
  overflow-x: auto;
}

.markdown-content :deep(pre) {
  background: #f8f8f8;
  padding: 12px;
  border-radius: 4px;
  overflow-x: auto;
}

.markdown-content :deep(code) {
  font-family: 'Courier New', monospace;
  font-size: 0.9em;
}

.markdown-content :deep(blockquote) {
  border-left: 3px solid #ddd;
  padding-left: 12px;
  color: #666;
  margin-left: 0;
}

.input-area {
  padding: 16px;
  background: white;
  border-top: 1px solid #eee;
  display: flex;
  gap: 12px;
}

textarea {
  flex: 1;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  resize: none;
  font-size: 16px;
  transition: border 0.3s;
}

textarea:focus {
  outline: none;
  border-color: #1890ff;
}

button {
  padding: 0 20px;
  height: 48px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s;
}

button:hover:not(:disabled) {
  background: #1482e6;
}

button:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

.loading-indicator {
  padding: 16px;
  text-align: center;
}

.typing-indicator {
  display: inline-flex;
  padding: 8px 16px;
  background: #eee;
  border-radius: 18px;
}

.typing-indicator span {
  height: 8px;
  width: 8px;
  margin: 0 2px;
  background-color: #999;
  border-radius: 50%;
  display: inline-block;
  animation: typing 1s infinite ease-in-out;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%,
  100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-5px);
  }
}

@media (max-width: 768px) {
  .chat-container {
    max-width: 100%;
  }

  .message-content {
    max-width: 90%;
  }
}
</style>
